<?php
/**
 * 用户控制器
 * @author e5
 *
 */
class UserController extends CommonController{
	private $db;
	public function __init(){
		parent::__init();
		$this->db = K("User");
	}
	/**
	 * 用户注册
	 */
	public function register(){
		//如果用户已登陆则跳到前台首页
		if (session("uname") && session("uid")) go(U("Index/index"));
		if (IS_POST){
			//判断验证码
			if (strtoupper($_POST['code']) != $_SESSION['code']) $this->error("验证码错误");
			//添加用户
			$uid = $this->db->register();
			if (!$uid) $this->error($this->db->error);
			//添加成功后写入session
			session("uid",$uid);
			session("uname",Q("post.username"));
			$this->success("注册成功",U("Index/index"));
		}
		$this->dis("register");
	}
	/**
	 * 异步判断用户是否存在
	 */
	public function ajaxUsername(){
		$uname = Q("post.username");
		if (!$uname) exit();
		if ($this->db->where("uname='{$uname}'")->count() > 0){
			echo 1;
			exit();
		}else {
			echo 0;
			exit();
		}
		exit();
	}
	/**
	 * 用户登陆
	 */
	public function login(){
		//如果用户已登陆则跳到前台首页
		if (session("uname") && session("uid")) go(U("Index/index"));
		if (IS_POST){
			$uname = Q("post.username");
			$upwd = Q("post.password");
			//验证是否为空
			if (!$uname) $this->error("用户名不能为空");
			if (!$upwd) $this->error("密码不能为空");
			$upwd = md5($upwd);
			//查询uid和密码
			$uid = $this->db->field("uid,upwd")->where("uname='{$uname}'")->find();
			if (!$uid) $this->error("用户不存在");
			if ($upwd != $uid['upwd']) $this->error("密码错误");
			//登陆成功，写入session
			session("uid",$uid['uid']);
			session("uname",$uname);
			$this->success("登陆成功");
		}
		$this->dis("login");
	}
	/**
	 * 用户退出
	 */
	public function out(){
		session(null);
		$this->success("退出成功",U("Index/index"));
	}
	/**
	 * 显示验证码
	 */
	public function code(){
		$code = new Code();
		$code->show();
	}
}